/**
 * Created by fdg282 on 2017/9/20.
 */
//细节图片展示
function imgShow(videos){
    //获取小图片
    //模拟ajax
    if(videos !== null){
        var bigImgbox =  $(".left_img_big");
        var miniImgbox = $(".left_img_tab");
        var bigVideobox = $(".js_video_box");
        var imgList;
        $.each(videos,function(i,id){
            if(id.source_type == 0){
                id.source_link=null
            }
            var img_url = id.source_url;
            //var img_url = checkImgExists(id.source_url);
            imgList = '<li id='+id.id+'><div><a href="javascript:;"><img src='+img_url+' mid='+img_url+' big='+img_url+' alt='+id.goods_name_cn+'></a><video  class="video-js  vjs-big-play-centered video detail_video " controls preload="none"  poster="" src='+id.source_link+' type="video/mp4"></video></div></li>';
            miniImgbox.append(imgList);
           //开始渲染第一个图片、视频
            var tabImg = $(".left_img_tab li:first-child").addClass('tb-selected').find('img').attr('mid');
            var tabvideo = $(".left_img_tab li:first-child").find('video').attr('src');
            var tabAlt = $(".left_img_tab li:first-child").addClass('tb-selected').find('img').attr('alt');
            var imgUrl = '<img src='+tabImg+' alt='+tabAlt+' rel='+tabImg+' class="jqzoom mid" />';
            var videoUrl = '<video  class="video-js  vjs-big-play-centered video detail_video" controls preload="none"  poster="" src='+tabvideo+' type="video/mp4" id="dVideo01"></video>';
            bigImgbox.find('.item_img_show').html(imgUrl);
            bigVideobox.html(videoUrl);
            //视频播放
            if(bigVideobox.find('video').attr("src")!='null'){
                $('.icon-video').show();
                $(".js_video_box video").attr('src',$(".tb-selected").children('video').attr("src")).attr('id','dVideo'+$(this).parents('.tb-selected').attr("id"));
                if($('.js_video_box').hasClass('hide')){
                    $(".icon-video").click(function(){
                        $(".zoomDiv,.zoomMask").hide();
                        $(this).hide();
                        $('.item_img_show').hide().siblings('.js_video_box').removeClass('hide');
                        var videoUrl = bigVideobox.children('video').attr('src');
                        var videoUrlID = bigVideobox.children('video').attr('id');
                        videojs(videoUrlID,{}, function() {
                            var myPlayer = this;
                            $(".js_video_box video").attr("src", videoUrl);
                            myPlayer.src(videoUrl);
                            myPlayer.load(videoUrl);
                            myPlayer.play();
                            myPlayer.on("ended", function(){
                                $(".js_icon").show();
                                $('.item_img_show').show().siblings('.js_video_box').addClass('hide');

                            });
                            myPlayer.on("pause",function(){
                                $(".js_icon").show();
                            })
                        });
                    });
                }else {

                }
            }else{
                $(".left_img_big .icon").removeClass('icon-video');
            }
             //小图切换
        $(".left_img_tab li a").mouseenter(function(){
              $(".left_img_big .icon").addClass('icon-video');
                $('.item_img_show').show().siblings('.js_video_box').addClass('hide');
                $('.icon-video').hide();
                $(".zoomDiv,.zoomMask").show();
                $(this).parents("li").addClass("tb-selected").siblings('li').removeClass("tb-selected");
                //赋值img属性
                $(".jqzoom").attr('src',$(this).find("img").attr("mid")).attr('rel',$(this).find("img").attr("big"));
                //视频播放
                if($(this).siblings('video').attr("src")!='null'){
                    $('.icon-video').show();
                    $(".js_video_box video").attr('src',$(this).siblings('video').attr("src")).attr('id','dVideo'+$(this).parents('li').attr("id"));
                    if($('.js_video_box').hasClass('hide')){
                        $(".icon-video").click(function(){
                            $(".zoomDiv,.zoomMask").hide();
                            $(this).hide();
                            $('.item_img_show').hide().siblings('.js_video_box').removeClass('hide');
                            var videoUrl = $(".tb-selected").children('video').attr("src");
                            var  videoUrlID = bigVideobox.children('video').attr('id');
                            videojs(videoUrlID,{}, function() {
                                var myPlayer = this;
                                $(".js_video_box video").attr("src", videoUrl);
                                myPlayer.src(videoUrl);
                                myPlayer.load(videoUrl);
                                myPlayer.play();
                                myPlayer.on("ended", function(){
                                    $(".js_icon").show();
                                    $('.item_img_show').show().siblings('.js_video_box').addClass('hide');

                                });
                                myPlayer.on("pause",function(){
                                    $(".js_icon").show();
                                })
                            });
                        });
                    }else {

                    }
                }else{
                    $(".left_img_big .icon").removeClass('icon-video');
                }
            });
            $(".left_img_big>.img").mouseenter(function(){
                $(".jqzoom").imagezoom();
            });
        });
    }
}

function checkImgExists(imgurl){
    var default_img = bath_url + "/uploads/2017-10-20/150848897870422.png";
    var width_img;
    width_img = getImageWidth(imgurl,imgSS);
    if(eval(width_img) > 0){
        return imgurl;
    }else{
        return default_img;
    }
}

function imgSS(width){
    console.info(width);
    return width;
}

function getImageWidth(url){
    var img = new Image();
    img.src = url;

    // 如果图片被缓存，则直接返回缓存数据
    if(img.complete){
        callback(img.width);
    }else{
        // 完全加载完毕的事件
        img.onload = function(){
            callback(img.width);
        }
    }

}

function colorList(){
    var colorList = $(".detail_color ul li");
    var styleList1 = $(".style_list_2 li");
    var styleList2 = $(".detail_style select");
    var priceList = $(".price_info");
    var sale_price = $('span.price').find('span').html();
    var market_price = $('span.price').find('del').eq(1).html();

    var colorSize = colorList.length;
    var spec = 0;
    var color = 0;
    if(colorSize>=12){
       colorList.parents(".detail_color").addClass("color_scroll")
    }
    if(styleList1.length>4){
        styleList1.parents('ul').hide().siblings('.s-1').show();
    }else {
        styleList1.parents('ul').show().siblings('.s-1').hide();
    }

    if(eval(sale_price) == eval(market_price)){
        $('span.price').find('del').hide();
    }
    $('span.price').find('span').html(toThousands(sale_price));
    $('span.price').find('del').eq(1).html(toThousands(market_price));
    /*只有规格与颜色都选择时才显示一个价格，其他显示价格区间*/
    //选择颜色样式
    priceList.find("span.p_1").show().siblings("span.p_2").hide();
    color = $(".color_list").find('li.color_active').attr('g_color');
    spec = $('.style_list_2').find('li.style_active').attr('g_spec');
    colorList.each(function(){
        $(this).click(function () {
            if($(this).hasClass('color_active')){

            }else{
                $(this).addClass("color_active").siblings(".item").removeClass("color_active");
                spec = $('.style_list_2').find('li.style_active').attr('g_spec');
                color = $(".color_list").find('li.color_active').attr('g_color');
                appendPrice(spec,color);
            }

        })
    });
    //点选样式
    styleList1.each(function(){
       $(this).click(function(){
           if($(this).hasClass("style_active")){

           }else{
               $(this).addClass("style_active").siblings('li').removeClass("style_active");
               spec = $('.style_list_2').find('li.style_active').attr('g_spec');
               color = $(".color_list").find('li.color_active').attr('g_color');
               appendPrice(spec,color);
           }

       })
    });
    //选择下拉样式
    styleList2.change(function(){
        spec = $(this).val();
        color = $(".color_list").find('li.color_active').attr('g_color');
        appendPrice(spec,color);
    })
}

function appendPrice(spec,color){
    var min_price = 0;
    var max_price = 0;
    var main_goods_string = $('.main_goods_span').attr('data-value');
    var detail_color = $('.detail_color').length;//判断是否存在颜色规格
    getSale(spec,color,main_goods_string);
    getCoupon(spec,color,main_goods_string);
    if(!isNaN(spec) && isNaN(color)){
        if(detail_color == 0){
            var price = getSpec(spec,color);
            $.post("/goods/source-list",{spec:spec,main_goods_id:main_goods_string},success,'json');
            return false;
            function success(data){
                if(data.code == 200){
                    $('.left_img_tab').empty();
                    $(".left_img_big").find('.item_img_show').empty();
                    $(".js_video_box").empty();
                    if($('.js_video_box').hasClass('hide')){

                    }else{
                        $('.js_video_box').addClass('hide');
                    }
                    imgShow(data.val);
                    //pushPrice(price[3],price[4],price[5]);
                    pushPrice(price[3],price[4],price[5],price[6]);
                }
            }
        }else{
            var spec_price = getPrice(spec,1);
            min_price = Math.min.apply(null,spec_price);
            max_price = Math.max.apply(null,spec_price);
            pushPriceZone(min_price,max_price);
        }
    }
    if(isNaN(spec) && !isNaN(color)){
        spec_price = getPrice(color,2);
        min_price = Math.min.apply(null,spec_price);
        max_price = Math.max.apply(null,spec_price);
        pushPriceZone(min_price,max_price);
    }
    if(isNaN(spec) && isNaN(color)){
        var max_min_data = splitString($('.min_max_sale').attr('g_min_sale'));
        pushPriceZone(max_min_data[0],max_min_data[1]);
    }
    if(!isNaN(spec) && !isNaN(color)){
        var price = getSpec(spec,color);
        $.post("/goods/source-list",{spec:spec,main_goods_id:main_goods_string,spec_color:color},success,'json');
        return false;
        function success(data){
            if(data.code == 200){
                console.log(price);
                $('.left_img_tab').empty();
                $(".left_img_big").find('.item_img_show').empty();
                $(".js_video_box").empty();
                if($('.js_video_box').hasClass('hide')){

                }else{
                    $('.js_video_box').addClass('hide');
                }
                imgShow(data.val);
                //pushPrice(price[3],price[4],price[5]);
                pushPrice(price[3],price[4],price[5],price[6]);
                $('.main_goods_span').attr('data-shop',price[0]);
            }
        }
    }
}

//置换价格
function pushPrice(sale_price,market_price,sku,series){
    $(".price_info").find("span.p_1").children().eq(0).html(toThousands(sale_price,2));
    $(".price_info").find("del").eq(1).html(toThousands(market_price,2));
    $(".detail_info_num").find("span").html(sku);
    $('.detail_info_series').text(series != '' && series != null ? series+'系列' : '');
    if(eval(sale_price) == eval(market_price)){
        $(".price_info").find("del").hide();
    }else{
        $(".price_info").find("del").show();
    }
    $(".price_info").find("span.p_1").show().siblings("span.p_2").hide();
}

/*
function pushPrice(sale_price,market_price,sku){
    $(".price_info").find("span.p_1").children().eq(0).html(toThousands(sale_price,2));
    $(".price_info").find("del").eq(1).html(toThousands(market_price,2));
    $(".detail_info_num").find("span").html(sku);
    if(eval(sale_price) == eval(market_price)){
        $(".price_info").find("del").hide();
    }else{
        $(".price_info").find("del").show();
    }
    $(".price_info").find("span.p_1").show().siblings("span.p_2").hide();
}
*/

//价格带
function pushPriceZone(min_price,max_price){
    $(".price_info").find("span.p_2").children().eq(0).html(toThousands(min_price,2));
    $(".price_info").find("span.p_2").children().eq(1).html(toThousands(max_price,2));
    $(".price_info").find("span.p_2").show().siblings("span.p_1").hide();
}

//促销
function getSale(spec,color,main_goods_id){
    if(spec == undefined || spec == '' || spec == null){
        spec = 0;
    }
    if(color == undefined || color == '' || color == null){
        color = 0;
    }
    $.post("/goods/sale-list",{spec:spec,main_goods_id:main_goods_id,spec_color:color},success,'json');
    function success(data){
        if(data.code == 200){
            var result = data.val;
            if(result.length == 0){
                if($('.detail_price').hasClass('detail_price_2')){

                }else{
                    $('.detail_price').addClass('detail_price_2');
                }

                if($('.cx_info').hasClass('hide')){

                }else{
                    $('.cx_info').addClass('hide');
                }
            }else{
                if($('.detail_price').hasClass('detail_price_2')){
                    $('.detail_price').removeClass('detail_price_2');
                }
                if($('.cx_info').hasClass('hide')){
                    $('.cx_info').removeClass('hide');
                }
                $('#sale_info').empty();
                $('#sale_info').append('<option selected value="defalut">请选择促销活动</option>');
                for(var i=0;i<result.length;i++){
                    $('#sale_info').append('<option>'+result[i]['title']+'</option>');
                }
            }
        }
    }
}

//优惠券
function getCoupon(spec,color,main_goods_id){
    if(spec == undefined || spec == '' || spec == null){
        spec = 0;
    }
    if(color == undefined || color == '' || color == null){
        color = 0;
    }
    $.post("/goods/get-coupon",{spec:spec,main_goods_id:main_goods_id,spec_color:color},success,'json');
    function success(data){
        if(data.code == 200){
            var result = data.val;
            if(result.length > 0){
            	var html = '';
            	result.forEach(function(e){
            		var discount_html = '';
            		if(e.type == '1'){
            			discount_html = '¥<span class="h1">'+parseFloat(e.discount_price)+'</span>元'
            		}else if(e.type == '2' || e.type == '3'){
            			if(coupon_type != ''){
            				for(val in coupon_type){
            					if(val == e.type){
            						discount_html = '<span class="h1">'+coupon_type[val]+'</span>';
            					}
            				}
            			}
            		}
            		html += '<input name="coupon_id[]" value="'+e.id+'" type="hidden"/><li class="item '+(e.type == '1' ? 'y_500' : 'j_8')+'">'+
                    '<div class="item_info">'+
                    '<h1 class=" yhj_price">'+discount_html+'</h1>'+
                    '<span class="yhj_price_go">'+e.title+'</span>'+
                    '<time class="yhj_time">'+e.coupon_end_time+'</time>'+
                    '<div class="item_layer ">'+
                    '<p class="yhj_info  yhj_info_hide">'+e.content+'</p>'+
                    '<span class="icon fa fa-info-circle "></span>'+
                    '</div>'+
                    '<div class="yhj_tips"></div>'+
                    '</div>'+
                    '</li>';
            	});
            	$('.get-coupon').removeClass('hide');
            }else{
            	var html = '<input name="coupon_id[]" value="" type="hidden"/><h3 class="info infoerror">相关优惠券您已领取完，详情请点击下方点击查看</h3>';
            	$('.get-coupon').addClass('hide');
            }
            $('#yhj_layer').find('.user_yhj_item').html(html);
        }
    }
}

//格式化金额
function toThousands(s,n){
    n = n > 0 && n <= 20 ? n : 2;
    s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
    var l = s.split(".")[0].split("").reverse(),
        r = s.split(".")[1];
    t = "";
    for(i = 0; i < l.length; i ++ )
    {
        t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
    }
    //return t.split("").reverse().join("") + "." + r;
    return t.split("").reverse().join("");
}

//type=1 规格   type=2 颜色
function getPrice(spec_color,type){
    var spec_price = new Array();
    if(type == 1){
        $('.spec_detail_span').each(function(){
            var goods_data = splitString($(this).attr('data-value'));
            if(eval(spec_color) == eval(goods_data[1])){
                spec_price.push(goods_data[3]);
            }
        })
    }else{
        $('.spec_detail_span').each(function(){
            var goods_data = splitString($(this).attr('data-value'));
            if(eval(spec_color) == eval(goods_data[2])){
                spec_price.push(goods_data[3]);
            }
        })
    }
    return spec_price;
}
//0:goods_id  1:spec  2:spec_color  3:sale_price  4:market_price
function getSpec(spec,color){
    var price = new Array();
    $('.spec_detail_span').each(function(){
        var goods_data = splitString($(this).attr('data-value'));
        if(eval(goods_data[2]) == 0){
            if(eval(spec) == eval(goods_data[1])){
                price = goods_data[3];
            }
        }else{
            if(eval(spec) == eval(goods_data[1]) && eval(goods_data[2]) == eval(color)){
                price = goods_data;
            }
        }
    });
    return price;
}

function splitString(string){
    if (string!==null) {
        return string.split("|");
    }else{
        console.log(string)
    }
}

function detailbtns(){
    //下载优惠劵
//    $('.js_down').click(function(){
//        $.layerShow("领取优惠劵成功","请会员中心查看已加入的优惠劵，跳转下载优惠劵页面");
//    });
	//下载优惠劵
    $('.js_down').on('click',function(){
    	var coupon_id = [];
    	$('#yhj_layer').find('input[name="coupon_id[]"]').each(function(){
    		if($(this).val() != ''){
    			coupon_id.push($(this).val());
    		}
    	});
    	if(coupon_id.length == 0){
    		$('#yhj_layer').fadeIn(300);
	        $('html').addClass('noscroll');
	        $(window).scrollTop(100);
    	}else{
    		$.post('/goods/receive-coupon',{coupon_id:coupon_id},success,'json');
        	function success(data){
        		if (data.code == 200) {
        			$('#yhj_layer').fadeIn(300);
        	        $('html').addClass('noscroll');
        	        $(window).scrollTop(100);
        		}else if(data.code == 404){
        			window.location.href="/login/index";
        		}else{
        			alert(data.val);
        		}
        	}
    	}
        $('#yhj_close').on('click',function(){
            $('#yhj_layer').fadeOut(300);
            $('html').removeClass('noscroll');
        })
    });
    //加入心愿单
    $('.js_inset_hart').click(function(){
        var goods_id  =$('.main_goods_span').attr('data-shop');
        $.post('/goods/goods-collection',{goods_id:goods_id},function success(data) {
            if (data.code == 200) {
                $('.js_inset_hart').children('.icon').slideUp();
                $('.js_inset_hart').children('.icon').addClass('icon-hart-active');
                $('.js_inset_hart').children('.icon').slideDown();
                var countSum = parseInt($("#hart-count").text());
                countSum++;
                $("#hart-count").text(countSum);
                //回传后端处理
                $.layerShow("添加心愿单成功", "您已成功添加此商品到心愿单，请到会员中心查看");
            }
            if(data.code == 202){
                $('.js_inset_hart').children('.icon').slideUp();
                $('.js_inset_hart').children('.icon').removeClass('icon-hart-active');
                $('.js_inset_hart').children('.icon').slideDown();
                var countSum = parseInt($("#hart-count").text());
                countSum--;
                $("#hart-count").text(countSum);
                //回传后端处理
                $.layerShow("删除心愿单成功","您已成功在心愿单中删除此商品，请到会员中心查看");
            }
            if(data.code == 500){
                window.location.href = data.url;
            }
            if(data.code == 502 || data.code == 503){
                $.layerShow("操作失败", data.val);
            }
        },'json');
    });
    //分享
    $('.js_fx').click(function(){
        if($(this).parents().find(".wechat_fx_layer").is('.hide')){
            $(".btn-group .wechat_fx_layer").removeClass("hide").addClass('show');
            //$.layerShow("分享成功","亲爱的上帝，感谢您的分享！");
        }else {
            $(".btn-group .wechat_fx_layer").addClass('hide').removeClass("show")
        }
    })
}

colorList();
detailbtns();

$('#sale_info').on('change',function(){
	var url = $(this).val();
	window.open(url);
});